package com.kx.ssm.utils;

import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

/**
 * @ClassName StringUtils
 * @Author Sun
 * @Date 2021/5/23 13:44
 */
public class StringUtils {
    /**
     * 判断字符串是否为空
     * @param str
     * @return
     */
    public static boolean isEmpty(String str){
        return str==null||"".equals(str);
    }

    /**
     * 获取随机字符串的方法
     * @param length
     * @return
     */
    public static String getRandomString(int length){
        StringBuffer stringBuffer = new StringBuffer();
        int count=0;
        while (count <= length - 1) {
            int i= (int) (Math.random()*123);
            if (i >= 48 && i <= 57 || i >= 65 && i <= 90 || i >= 97 && i <= 122) {
                stringBuffer.append((char)i);
                count++;//放在这里不放在外面的原因是万一不符合要求应该重新生成
            }
        }

        return stringBuffer.toString();
    }

    public static String getMd5(String source,String salt,int times){
        if(times==0){
            return source;
        }
        StringBuffer buffer = new StringBuffer(salt);
        buffer.append(source);
        buffer.append(salt);
        String newSource = buffer.toString();
        String md5 = DigestUtils.md5DigestAsHex(newSource.getBytes(StandardCharsets.UTF_8));
        return getMd5(md5, salt, --times);
    }
}
